package com.example.stock.controller;

import com.example.stock.controller.dto.FundUnitsDTO;
import com.example.stock.excel.FundUnits;
import com.example.stock.model.WeekDetail;
import com.example.stock.service.FundUnitsService;
import com.example.stock.service.WeekDataService;
import com.example.stock.util.Result;
import com.example.stock.util.ResultGenerator;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@CrossOrigin(origins = "*")
@RequestMapping("fundUnits")
@RestController
public class FundUnitsController {

    @Autowired
    FundUnitsService fundUnitsService;

    @Autowired
    WeekDataService weekDataService;

    @GetMapping("/{stock}")
    public Result index(@PathVariable String stock) {
        List<FundUnits> fundUnits = fundUnitsService.getFundUnits(stock);

        // 获取当时的收盘价格
        List<WeekDetail> weekRawData = weekDataService.getWeekRawData(stock);
        Map<String, Double> closeMap = weekRawData.stream().collect(Collectors.toMap(WeekDetail::getDate, WeekDetail::getClose));

        List<FundUnitsDTO> ret = new ArrayList<>();
        fundUnits.forEach(item -> {
            FundUnitsDTO fundUnitsDTO = new FundUnitsDTO();
            BeanUtils.copyProperties(item, fundUnitsDTO);

            fundUnitsDTO.setClose(closeMap.get(item.getDate()));
            ret.add(fundUnitsDTO);
        });

        return ResultGenerator.genSuccessResult(ret);
    }
}